import time
from threading import Thread
from tkinter import *
import tkinter as tk
from tkinter import messagebox, ttk
import os
import  requests
from lxml import html
from threading import Thread
import math

etree = html.etree


selUrl = None
baseUrl = "https://www.yingsx.com"
headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0"
}

script_path = os.path.abspath(__file__)
current_dir = os.path.dirname(script_path)

def download(progress_var, done_var):
    result = ["" for i in range(30)]
    resp = requests.get(selUrl, headers=headers)
    resp.encoding = "utf-8"
    parser = etree.HTMLParser(encoding='utf-8')
    tree = etree.HTML(resp.text, parser)

    dds = tree.xpath("//*[@id='list']/dl/dd")
    title = "".join(tree.xpath("//*[@id='info']/h1/text()"))
    print(title)
    def downBook(start, end, index):
        for i in range(start, end):
            txt = dds[i].xpath("./a/text()")[0]
            hrf = dds[i].xpath("./a/@href")[0]
            print(txt)
            rp = requests.get(baseUrl + hrf, headers=headers)
            rp.encoding = "utf-8"
            tre = etree.HTML(rp.text, parser)

            result[index] += txt + "\n";
            content = tre.xpath("//*[@id='content']/text()")
            if len(content) > 0:
                content = "".join(content)
                result[index] += content + "\n"

    num = math.ceil((len(dds) - 9) / 30)

    ts = [0 for i in range(30)]
    for i in range(30):
        s = (i * num) + 9
        e = s + num
        e = e if len(dds) > e else len(dds)
        ts[i] = Thread(target=downBook, args=(s, e, i))

    for t in ts:
        t.start()

    for i in range(30):
        progress_var.set(i*3)
        ts[i].join()

    with open(title + ".txt", mode="w", encoding="utf-8") as f:
        f.write("\n".join(result))

    done_var.set(True)  # 设置任务完成

def show_loading_dialog(parent, task_function, *args, **kwargs):
    """显示加载提示对话框，并运行一个耗时任务"""
    # 创建加载对话框
    loading_dialog = tk.Toplevel(parent)
    loading_dialog.title("Loading...")
    loading_dialog.geometry("300x100+400+200")
    loading_dialog.resizable(False, False)
    loading_dialog.transient(parent)  # 使对话框模态（相对于父窗口）
    loading_dialog.grab_set()  # 确保对话框获得所有输入焦点

    # 创建进度条和标签
    progress_var = tk.DoubleVar(value=0.0)
    done_var = tk.BooleanVar(value=False)
    progress_bar = ttk.Progressbar(loading_dialog, orient="horizontal", length=200, mode="determinate", variable=progress_var)
    progress_bar.pack(pady=10)
    status_label = tk.Label(loading_dialog, text="Please wait, loading...")
    status_label.pack()

    # 在新线程中运行耗时任务
    task_thread = Thread(target=task_function, args=(progress_var, done_var) + args, kwargs=kwargs)
    task_thread.start()

    # 检查任务是否完成
    def check_done():
        if done_var.get():
            loading_dialog.destroy()  # 关闭对话框
        else:
            # 每100毫秒检查一次
            loading_dialog.after(100, check_done)

    # 开始检查循环
    check_done()


def clear_entry(event=None):
    if entry.get() == "请输入小说名":
        entry.delete(0, tk.END)
    entry.config(foreground="black")  # 确保文本颜色正确

def down_xs():
    if selUrl:
        show_loading_dialog(win,download)

def search_xs():
    name = entry.get()
    searchUrl = "https://www.yingsx.com/cse/search?q="+name+"&s="
    resp = requests.get(searchUrl, headers=headers)
    resp.encoding = "utf-8"
    parser = etree.HTMLParser(encoding='utf-8')
    tree = etree.HTML(resp.text, parser)
    xs_list = tree.xpath("//*[@id='main']//div[@class='novelslist2']/ul/li")
    for item in treeview.get_children():
        treeview.delete(item)
    for i in range(1,len(xs_list)):
        xs_name = xs_list[i].xpath("./span[2]/a/text()")[0]
        xs_url = xs_list[i].xpath("./span[2]/a/@href")[0]
        xs_author = str(xs_list[i].xpath("./span[4]/text()")[0]).strip()
        xs_time = str(xs_list[i].xpath("./span[6]/text()")[0]).strip()
        xs_status = str(xs_list[i].xpath("./span[7]/text()")[0]).strip()
        treeview.insert("", "end",
                        values=(f"{xs_name}", f"{xs_author}", f"{xs_time}", f"{xs_status}"),text=f"{xs_url}")



def on_treeview_select(event):
    sels = treeview.selection()
    if(len(sels)<=0):
        return
    item_text = treeview.item(sels[0], "text")
    global selUrl
    selUrl = baseUrl + item_text
    print(selUrl)

win = Tk()  # 实例化窗口
win.title('Xs下载')
win.minsize(600, 400)

entry = Entry(win,width=40)
entry.insert(0, "请输入小说名")
entry.config(foreground="gray")  # 设置初始文本颜色为灰色，模仿提示效果
entry.bind("<FocusIn>", clear_entry)  # 绑定点击事件来清除文本
entry.pack(pady=(10,0))

btn = Button(win,text="搜索",command=search_xs).pack(pady=5)
btnDown = Button(win,text="下载",command=down_xs).pack(pady=5)

treeview = ttk.Treeview(win,columns=("c1", "c2","c3","c4"), show="headings")

treeview.column('c1', anchor=tk.CENTER)
treeview.column('c2', anchor=tk.CENTER)
treeview.column('c3', anchor=tk.CENTER)
treeview.column('c4', anchor=tk.CENTER)

treeview.heading("c1", text="名称")
treeview.heading("c2", text="作者")
treeview.heading("c3", text="更新时间")
treeview.heading("c4", text="状态")

treeview.bind("<<TreeviewSelect>>", on_treeview_select)

treeview.pack(fill=tk.BOTH, expand=True,padx=10,pady=(0,5))
win.mainloop()
